#include "tcpclient.h"
#include "quiwidget.h"
#include "commsignalslot.h"
#include "mof_protocol.h"

#include "mainwindow.h"
#include <QDebug>

TcpClient::TcpClient(QObject *parent) : QObject(parent), isConnect(false)
{
    tcpSocket = new QTcpSocket(this);
    timer = new QTimer(this);
    timer->setInterval(1000);

    connect(timer, &QTimer::timeout, this, &TcpClient::SlotTimer);

    connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(disconnected()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));

    connect(this, &TcpClient::tcpSignalLog, CommSignalSlot::Instance(), &CommSignalSlot::CommSlotLog);
}

void TcpClient::SlotTimer()
{
    //if(!isConnect) return;

    mof_protocol::Instance()->run();
}

TcpClient* TcpClient::Intance()
{
    static TcpClient tcp;

    return &tcp;
}

void TcpClient::tcpSlotStart(const QString& ip, quint16 port)
{
    tcpSocket->connectToHost(ip, port);
    emit tcpSignalLog(CommSignalSlot::logDateTime, ip, QString::number(port));
}

void TcpClient::tcpClientStop()
{
    tcpSocket->disconnectFromHost();
}

bool TcpClient::isTcpConnect()
{
    return isConnect;
}

void TcpClient::connected()
{
    isConnect = true;
    emit tcpSignalLog(CommSignalSlot::logSTR, ">>", "tcpConnect");

    timer->start();
}

void TcpClient::disconnected()
{
    isConnect = false;
    tcpSocket->abort();
    emit tcpSignalLog(CommSignalSlot::logSTR, ">>", "tcpStop");
}

void TcpClient::readData()
{
    QByteArray data = tcpSocket->readAll();
    if (data.length() <= 0) {
        return;
    }

    QString log = QUIHelper::byteArrayToHexStr(data);
    emit tcpSignalLog(CommSignalSlot::logDateTime, "RCV", log);

    //sendData("{\"ReportTime\":\"2020-11-24 22:50:10\"}");
    mof_protocol::Instance()->push(data.data(), data.length());

    mof_protocol::Instance()->mof_pharse();
}

void TcpClient::sendData(const QByteArray &data)
{
    if(isConnect) {
        QString log = QUIHelper::byteArrayToHexStr(data);

        qDebug() << "tcp send: " << data.length() << " " << log.length();
        emit tcpSignalLog(CommSignalSlot::logDateTime, "SND", log);

        tcpSocket->write(data);
    }
}
